package services

import (
	"TaskAssignmentSystem/internal/admin/dao"
	"TaskAssignmentSystem/pkg/db/mysql"
	"gorm.io/gorm"
)

type CommonService[T any] struct {
	Tx          *gorm.DB
	Page        int64                  `json:"page"`
	PageSize    int64                  `json:"page_size"`
	Result      T                      `json:"result"`
	Order       string                 `json:"order"`
	Query       map[string]interface{} `json:"query"`
	WhereStr    []string               `json:"where_str"`
	LeftJoin    []string               `json:"left_join"`
	SelectField *string                `json:"select_field"`
}

func (u *CommonService[T]) SelectList() (res *dao.PageResponse[T], err error) {
	ug := &dao.Page[T]{
		Page:        u.Page,
		PageSize:    u.PageSize,
		Order:       u.Order,
		WhereStr:    u.WhereStr,
		LeftJoin:    &u.LeftJoin,
		SelectField: u.SelectField,
	}

	where := u.Query
	err = ug.SelectPage(where)
	pageResponse := dao.NewPageResponse(ug)
	return pageResponse, err
}
func (u *CommonService[T]) Update(set map[string]interface{}) (err error) {
	var common dao.Common[T]
	common.Query = u.Query
	return common.Update(set).Error
}

func (u *CommonService[T]) BatchUpdate(ids []uint, set map[string]interface{}) (err error) {
	var common dao.Common[T]
	common.Tx = u.Tx
	return common.BatchUpdate(ids, set).Error
}

func (u *CommonService[T]) Remove() (err error) {
	var common dao.Common[T]
	common.Tx = u.Tx
	return common.RemoveByWhere(u.Query).Error
}

func (u *CommonService[T]) RemoveUnscoped() (err error) {
	var common dao.Common[T]
	common.Tx = u.Tx
	common.CustomWhere = u.WhereStr
	return common.RemoveUnscopedWhere(u.Query).Error
}

func (u *CommonService[T]) Count() (count int64, err error) {
	var common dao.Common[T]
	common.Tx = u.Tx
	common.CustomWhere = u.WhereStr
	common.Query = u.Query
	return common.Count(u.Query)
}

func CheckUserWithProjectPermission(projectId string, uid uint) bool {
	_db := mysql.GetDB()
	//检测当前用户有么有改项目的权限
	var user dao.SystemUserRestriction
	if err := _db.Model(&dao.SystemUserRestriction{}).Where(map[string]interface{}{"project_id": projectId, "system_user_id": uid}).First(&user).Error; err != nil {
		switch err {
		case gorm.ErrRecordNotFound:
			return false
		default:
			return false
		}
	} else {
		return true
	}
}
